package com.tanhua.server.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.service.RecommendUserService;
import com.tanhua.server.service.TodayBestService;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserService;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TodayBestServiceImpl implements TodayBestService {
    @Autowired
    private RecommendUserService recommendUserService;


    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Override
    public TodayBest queryTodayBest() {
        /*User user = this.userService.queryUserByToken(token);
        if (user == null){
            //token 不合法或者已经过期
            return null;
        }*/

        //直接从ThreadLocal中获取user
        User user = UserThreadLocal.get();
        //查询推荐用户
        TodayBest todayBest = this.recommendUserService.queryTodayBest(user.getId());

        if (todayBest == null){
            //未查询到数据，给出默认的推荐用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
            todayBest.setFateValue(80L);
        }
        //补全个人信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(todayBest.getId());
        if (null == userInfo){
            return null;
        }
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");

        return todayBest;
    }

    @Override
    public PageResult queryRecommendation(RecommendUserQueryParam queryParam) {
        /*//验证token
        User user = this.userService.queryUserByToken(token);
        if (user == null){
            //token 不合法或者已经过期
            return null;
        }*/
        //直接从ThreadLocal中获取user
        User user = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());

        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), queryParam.getPage(), queryParam.getPagesize());
        //记录集
        List<RecommendUser> records = pageInfo.getRecords();
        System.out.println(records);
        if (CollectionUtils.isEmpty(records)){
            //没有查询到推荐用户列表
            return pageResult;
        }
        //填充个人信息

        //收集推荐用户的id
        //使用set可以去除重复的id
        Set<Long> userIds = new HashSet<>();
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();

        //用户id参数
        queryWrapper.in("user_id", userIds);
        //需要性别参数查询
        if (StringUtils.isEmpty(queryParam.getCity())){
            queryWrapper.eq("sex", StringUtils.equals(queryParam.getGender(), "man") ? 1:2);
        }
        //需要城市参数查询
        if (StringUtils.isNotEmpty(queryParam.getCity())){
            queryWrapper.like("city", queryParam.getCity());
        }
        //设置年龄参数，条件：小于等于
        if (queryParam.getAge() != null){
            queryWrapper.le("age",queryParam.getAge());
        }
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        if (CollectionUtils.isEmpty(userInfoList)){
            return pageResult;
        }
        List<TodayBest> todayBestList = new ArrayList<>();
        TodayBest todayBest;
        for (UserInfo userInfo : userInfoList) {
            todayBest = new TodayBest();
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");

            //缘分值
            for (RecommendUser record : records) {
                if(record.getUserId().longValue() == userInfo.getUserId().longValue()){
                    double score = Math.floor(record.getScore());//取整,98.2 -> 98
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }
            todayBestList.add(todayBest);
        }
        //按照缘分值进行倒序排序(o1 - o1)
        Collections.sort(todayBestList,(o1, o2) -> new Long(o2.getFateValue() -o1.getFateValue()).intValue());

        pageResult.setItems(todayBestList);
        return pageResult;
    }
}
